package cn.qayy.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.BasisDTO;
import cn.qayy.dto.CashFlowDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.dto.PlansDTO;
import cn.qayy.po.Basis;
import cn.qayy.po.CashFlow;
import cn.qayy.po.Plan;
import cn.qayy.po.Policy;
import cn.qayy.po.Register;
import cn.qayy.service.ICashFlowService;
import cn.qayy.service.IPolicyService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.InitPlansUtil;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu 现金流量表
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/cashflow/")
public class CashFlowController {
	// 注入service
	@Resource(name = "cashFlowServiceImpl")
	private ICashFlowService cashFlowService = null;

	@Resource(name = "policyServiceImpl")
	private IPolicyService policyService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	/***
	 * 持久化中标库后，更新context缓存
	 * 
	 * @param list
	 */
	/*private void addToContext(List<CashFlow> list) {
		/***
		 * 获取项目上下文的共享数据
		 
		ServletContext servletContext = ServletContextUtils.getServletContext();
		// 中标库keys
		Set<String> pzKeys = (Set<String>) servletContext.getAttribute("pzKeys");
		for (CashFlow b : list) {
			pzKeys.add(StringUtil.concat(b.getProvince(), b.getCity(), b.getTerminal(), b.getProduct(), b.getPack(),
					b.getStime(), b.getEtime(), b.getId() + ""));
		}
	}*/
	/***
	 * 持久化中标库后，更新context缓存
	 * 
	 * @param list
	 */
	/*private void removeToContext(List<CashFlow> list) {
		/***
		 * 获取项目上下文的共享数据
		
		ServletContext servletContext = ServletContextUtils.getServletContext();
		// 中标库keys
		Set<String> pzKeys = (Set<String>) servletContext.getAttribute("pzKeys");
		for (CashFlow b : list) {
			pzKeys.remove(StringUtil.concat(b.getProvince(), b.getCity(), b.getTerminal(), b.getProduct(), b.getPack(),
					b.getStime(), b.getEtime(), b.getId() + ""));
		}
	}*/

	@ResponseBody
	@RequestMapping(value = "upload")
	public Object uploadCashFlowList(@RequestParam("excelFile") MultipartFile file) {
		Msg msg = null;
		int listSize = 0; // excel记录数
		int doSize = 0; // 执行成功记录数
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file, CashFlowDTO.class);
			/**用户上传的总记录数**/
			MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
			listSize = StringUtil.parseInt(msgInfo.getErr_num());
			
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 前台提示消息
				// 验证不通过，前台提示消息
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// DB持久化
				//是否操作成功
				boolean isSucessful = false;
				
				List<Uploadable> listE = map.get("E");
				if (listE != null && !listE.isEmpty()) {
					// 待更新的实体list
					List<CashFlow> list = new ArrayList<CashFlow>(listE.size() + 1);
					for (Uploadable u : listE) {
						CashFlowDTO dto = (CashFlowDTO) u;
						// 封装数据
						CashFlow cashFlow = null;
						cashFlow= cashFlowService.selectCashFlowByID(StringUtil.parseInt(dto.getId()));
						if(cashFlow != null) {
							List<CashFlow> plist = new ArrayList<CashFlow>();
							plist.add(cashFlow);
							//removeToContext(plist);
							cashFlow.setByDTO(dto);
							cashFlow = initCount(cashFlow);
							list.add(cashFlow);
						}
					}
					if(!list.isEmpty()) {
						doSize = doSize + cashFlowService.updateByList(list);
						//addToContext(list);
						isSucessful = true;
					}
				}
				List<Uploadable> listN = map.get("N");
				if (listN != null && !listN.isEmpty()) {
					// 待新增的实体list
					List<CashFlow> list = new ArrayList<CashFlow>(listN.size() + 1);
					for (Uploadable u : listN) {
						CashFlowDTO dto = (CashFlowDTO) u;
						// 封装数据
						CashFlow cashFlow = new CashFlow();
						cashFlow.setByDTO(dto);
						cashFlow = initCount(cashFlow);
						list.add(cashFlow);
					}
					if(!list.isEmpty()) {
						doSize = doSize + cashFlowService.insertByList(list);
						//addToContext(list);
						isSucessful = true;
					}
				}
				if(isSucessful) {
					// 正常操作前台提示消息
					msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + listSize + "，请核查！");
				} else {
					throw new Exception();
				}
			}
		} catch (Exception e) {
			// 异常后的前台提示消息
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = "selectForList")
	public Object selectForList(CashFlowDTO dto, HttpServletRequest request) {
		Msg msg = null;
		try {
			PageInfo<CashFlow> pageInfo = cashFlowService.selectCashFlowBy(dto);
			msg = new Msg(Constant.SUCESSFUL_CODE, pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = "selectByID")
	public Object selectByID(@RequestParam Integer id) {
		Msg msg = null;
		try {
			CashFlow cashFlow = cashFlowService.selectCashFlowByID(id);
			msg = new Msg(Constant.SUCESSFUL_CODE, cashFlow);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = "saveOrUpdate")
	public Object saveOrUpdate(CashFlowDTO dto, HttpServletRequest request) {
		Msg msg = null;
		String flag = (String) request.getParameter("flag");
		if (flag.equals("N")) { // N:新增
			dto.setIsUpdate("N");
		} else if (flag.equals("E")) {// E:修改
			dto.setIsUpdate("E");
		}
		try {
			// 验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 验证不通过，前台提示消息
				/**
				 * 验证不通过，前台提示消息
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
			} else {// 验证通过，DB持久化
				List<Uploadable> listE = map.get(flag);
				if (listE != null && !listE.isEmpty()) {
					List<CashFlow> list = new ArrayList<CashFlow>(listE.size() + 1);
					for (Uploadable u : listE) {
						dto = (CashFlowDTO) u;
						// 封装数据
						CashFlow cashFlow = null;
						if (flag.equals("E")) {
							cashFlow= cashFlowService.selectCashFlowByID(StringUtil.parseInt(dto.getId()));
							if(cashFlow != null) {
								List<CashFlow> plist = new ArrayList<CashFlow>();
								plist.add(cashFlow);
								//removeToContext(plist);
								cashFlow.setByDTO(dto);
								cashFlow = initCount(cashFlow);
								list.add(cashFlow);
								
							}
						} else if(flag.equals("N")){
							cashFlow = new CashFlow();
							cashFlow.setByDTO(dto);
							cashFlow = initCount(cashFlow);
							list.add(cashFlow);
						}
					}
					if(!list.isEmpty()) {
						if (flag.equals("N")) { // N:新增
							cashFlowService.insertByList(list);
						} else if (flag.equals("E")) { // E:修改
							cashFlowService.updateByList(list);
						}
						//addToContext(list);
						/**
						 * 正常操作前台提示消息
						 */
						msg = new Msg(Constant.SUCESSFUL_CODE, Constant.SUCESSFUL_MSG);
					} else {
						throw new Exception();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<CashFlowDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(CashFlowDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("现金流",StringUtil.listToStrArray(CollectionConstant.cashFlow_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui.do")
	public ModelAndView ui(HttpServletRequest req) {
		ServletContext context = req.getSession().getServletContext();
		
		ModelAndView model = new ModelAndView();
		//获取年份
		model.addObject("years", CollectionConstant.years);
		//获取包装
		model.addObject("packs", CollectionConstant.packs);
		//获取现金流项目集合
		model.addObject("projects", CollectionConstant.projects);
		//获取部门
		model.addObject("deptJson",JSONObject.toJSONString(context.getAttribute("department"))); //json格式
		//获取项目
		model.addObject("proJson",JSONObject.toJSONString(context.getAttribute("project"))); //json格式
		//获取二级科目
		model.addObject("secondJson",JSONObject.toJSONString(context.getAttribute("secondLevel"))); //json格式
		//获取三级科目
		model.addObject("threeJson",JSONObject.toJSONString(context.getAttribute("threeLevel"))); //json格式
		//获取四级科目
		model.addObject("fourJson",JSONObject.toJSONString(context.getAttribute("fourLevel"))); //json格式
		model.setViewName("cashFlow_search");
		
		return model;
	}
	
	public CashFlow initCount(CashFlow cashFlow) throws Exception {
		//初始化生产折量和销售折量
		Plan p = new Plan();
		p.setProduct(cashFlow.getProduct());
		p.setPack(cashFlow.getPack());
		p.setCount(cashFlow.getCount());
		p.setXieyizhuangtai(cashFlow.getStripLine());
		p = InitPlansUtil.salesInit(p);
		cashFlow.setXsCount(p.getXsScount());
		cashFlow.setPCount(p.getScount());
		return cashFlow;
	}
	
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			CashFlowDTO dto = (CashFlowDTO)DownLoadUtil.get("CashFlowDTO");
			List<Integer> list = cashFlowService.selectIdsByMap(dto);
			if(list != null && list.size()>0) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.toString().length()-1);
			}
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
}
